import { AppDataSource } from "../data-source";
import { NextFunction, Request, Response } from "express";
import { Photo } from "../entity/Photo";
import { PhotoMetadata } from "../entity/PhotoMetadata.";

export class PhotoController {
  private photoRepository = AppDataSource.getRepository(Photo);
  private photoMetadataRepository = AppDataSource.getRepository(PhotoMetadata);

  async all(request: Request, response: Response, next: NextFunction) {
    return this.photoRepository.find();
  }

  async one(request: Request, response: Response, next: NextFunction) {
    const id = parseInt(request.params.id);

    // const photo = await this.photoRepository.findOne({
    //   where: { id },
    //   relations: ["metadata"],
    // });
    const photo = await this.photoRepository
      .createQueryBuilder("photo")
      .innerJoinAndSelect("photo.metadata", "metadata")
      .where("photo.id = :id", { id })
      .getOne();

    if (!photo) {
      return "unregistered photo";
    }
    return photo;
  }

  async save(request: Request, response: Response, next: NextFunction) {
    const { name, description, filename, views, isPublished } = request.body;
    const metadata = new PhotoMetadata();
    metadata.height = 100;
    metadata.width = 200;
    metadata.orientation = "landscape";
    metadata.compressed = true;
    metadata.comment = "this is a comment";

    const photo = Object.assign(new Photo(), {
      name,
      description,
      filename,
      views,
      isPublished,
      metadata,
    });

    return this.photoRepository.save(photo);
  }

  async remove(request: Request, response: Response, next: NextFunction) {
    const id = parseInt(request.params.id);

    let photoToRemove = await this.photoRepository.findOne({
      where: { id },
      relations: ["metadata"],
    });
    console.log(photoToRemove);
    if (!photoToRemove) {
      return "this photo not exist";
    }

    await this.photoRepository.remove(photoToRemove);

    const photoMetadata = await this.photoMetadataRepository.findOne({
      where: { id: photoToRemove.metadata.id },
    });

    console.log(photoMetadata);

    return "photo has been removed";
  }
}
